<%--
  Created by IntelliJ IDEA.
  User: nihaowzy
  Date: 2020/12/26
  Time: 20:36
  
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resource/layui/css/layui.css">
</head>
<body>
    <form class="layui-form layui-form-pane">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">头像</label>
                <div class="layui-inline">
                    <img id="userImg" style="width: 200px;solid :1px solid orange"
                         onerror="javascript:this.src='${pageContext.request.contextPath}/imgs/科比.jpg'"
                        src="${pageContext.request.contextPath}/${user.img}"/>
                </div>
            </div>
        </div>
        <div class="layui-form-item" style="margin-left: 110px">
            <button type="button" id="uploadBtn" class="layui-btn layui-btn-primary" lay-submit lay-filter="subBtnFilter">修改</button>
        </div>
    </form>

<script src="${pageContext.request.contextPath}/resource/layui/layui.js"></script>
<script>
    layui.use(['form','layer','jquery','upload'],function () {
        let form = layui.form;
        let layer = layui.layer;
        let $ = layui.jquery;
        let upload = layui.upload;
        let rootPath = "${pageContext.request.contextPath}";

        let opt = {
            elem:"#userImg",//文件上传的容器 触发文件上传的操作
            url:rootPath+"/user.do?service=uploadImg",//接受文件上传数据的接口
            accept:"file",//允许文件上传的类型 默认是images
            acceptMime:"images/*",//文件筛选框
            exts:"jpg|png|jpeg",//允许文件上传的后缀名
            auto:false,//选择文件上传后不进行网络请求 false
            bindAction:"#uploadBtn",
            field:"useImg",//隐藏文件域的name属性 网络请求中的name属性
            size:1024,
            choose:function (obj) {//选择文件后的回调
                //图片的预览
                obj.preview(function (index,file,result) {
                    //为图片设置Base64位的编码
                    $("#userImg").attr("src",result)
                });
            },

            done:function (rs,index,upload) {
                //rs文件返回数据 index文件索引用于多文件上传 upload文件上传对象可以上传失败时重新上传
                if (rs.code == 200){
                    //上传成功了
                    //修改登录框中的图片地址，URL
                    //获取上传图片的URL
                    let imgURL = rs.data;
                    //修改父窗口中的头像，
                    window.parent.document.getElementById("loginImg").src = imgURL;
                }

            }
        };

        upload.render(opt);
    })
</script>
</body>
</html>
